package org.xhystudy.rpc.registry.loadbalancer;

import org.xhystudy.rpc.common.ServiceMeta;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description: 轮询算法
 * @Author: Xhy
 * @gitee: https://gitee.com/XhyQAQ
 * @copyright: B站: https://space.bilibili.com/152686439
 * @CreateTime: 2023-04-30 21:40
 */
public class RoundRobinLoadBalancer implements ServiceLoadBalancer{

    private static AtomicInteger roundRobinId = new AtomicInteger(0);

    @Override
    public ServiceMeta select(List servers, int hashCode) {
        // 1.获取所有服务
        int size = servers.size();
        // 2.根据当前轮询ID取余服务长度得到具体服务
        roundRobinId.incrementAndGet();
        if (roundRobinId.get() == Integer.MAX_VALUE){
            roundRobinId.set(0);
        }
        return (ServiceMeta) servers.get(roundRobinId.get() % size);
    }
}
